<?php


namespace app\unify\controller;


use app\BaseController;
use app\unify\model\Config as ConfigModel;
use think\annotation\route\Validate;
use think\db\Query;
use think\facade\Db;
use think\Request;
use app\unify\validate\Config as ConfigValidate;


class Config extends BaseController
{
    /**
     * 配置列表
     *
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function index(Request $r)
    {
        $where = [];

        $keywords = $r->param('keywords');
        if ($keywords) {
            $where[] = ['title|name', 'LIKE', "%{$keywords}%"];
        }

        return ConfigModel::where($where)->withSearch(['keywords', 'groupId', 'status'], [
            'groupId' => $r->param('groupId'),
            'status' => $r->param('status'),
        ])->append(['typeName', 'statusName'])->order("serial ASC, id ASC")->paginate($this->limit);

    }


    /**
     * 配置表单
     *
     * @param mixed $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function form(mixed $id = 0): array
    {
        $groupList = \app\unify\model\ConfigGroup::order('serial ASC,id ASC')->select()->toArray();
        $data = [
            'groupList' => $groupList,
            'typeList' => ConfigModel::TYPE_LIST,
            'statusList' => ConfigModel::STATUS_LIST,
            'entity' => [
                'status' => ConfigModel::STATUS_ENABLE,
                'groupId' => $groupList[0]['id'],
                'type' => ConfigModel::TYPE_INPUT
            ]
        ];

        if ($id) {
            $entity = ConfigModel::find($id);
            $data['entity'] = $entity;
        }

        return $data;
    }

    /**
     * 新增配置
     *
     * @param \think\Request $request
     * @return string
     */
    #[Validate(ConfigValidate::class, scene: ConfigValidate::SAVE)]
    public function save(Request $request): string
    {
        $params = $request->param();

        $params['value'] = $params['default'];

        ConfigModel::create($params);

        return '操作成功';
    }

    /**
     * 配置信息
     *
     * @param int $id
     * @return array
     */
    public function read($id)
    {
        return ConfigModel::findOrEmpty($id)->append(['groupName'])->toArray();
    }


    /**
     * 修改配置
     *
     * @param \think\Request $request
     * @param int $id
     * @return string
     */
    #[Validate(ConfigValidate::class, scene: ConfigValidate::UPDATE)]
    public function update(Request $request, int $id): string
    {

        $config = ConfigModel::findOrEmpty($id);
        if ($config->isEmpty()) {
            throw new \Exception('未找到该配置');
        }

        $config->save($request->param());

        return '操作成功';
    }

    /**
     * @Notes 修改配置字段
     * @Author EdwardCho
     * @Date 2024/1/3
     * @Time 23:44
     * @Interface updateField
     * @param \think\Request $r
     * @param array $ids
     * @param $field
     * @param $value
     * @return string
     */
    #[Validate(ConfigValidate::class, scene: ConfigValidate::UPDATE_FIELD)]
    public function updateField(Request $r, array $ids, $field, $value)
    {
        ConfigModel::update([
            $field => $value
        ], [
            ['id', 'in', $ids]
        ]);

        return '操作成功';

    }

    /**
     * @Notes 系统设置
     * @Author EdwardCho
     * @Date 2023/12/14
     * @Time 01:03
     * @Interface setting
     */
    #[Validate(ConfigValidate::class, scene: ConfigValidate::SET_VALUES)]
    public function setValues(Request $r)
    {
        $data = $r->param('data');

        Db::transaction(function () use ($data) {
            foreach ($data as $item) {
                $where = [];
                $where[ConfigModel::getPrimaryKey()] = $item['id'];
                ConfigModel::update([
                    'value' => $item['value']
                ], $where);
            }
        });
    }

    /**
     * 删除配置
     *
     * @param array $ids
     * @return string
     */
    #[Validate(ConfigValidate::class, scene: ConfigValidate::DELETE)]
    public function delete(array $ids): string
    {
        Db::transaction(function () use ($ids) {
            ConfigModel::destroy(function (Query $q) use ($ids) {
                $q->where([
                    [ConfigModel::getPrimaryKey(), 'in', $ids]
                ]);
            });
        });


        return '删除成功';
    }

    /**
     * @Notes 初始化参数
     * @Author EdwardCho
     * @Date 2024/1/5
     * @Time 15:27
     * @Interface initConfig
     * @return array
     */
    public function initConfig()
    {
        return [
            'base_site_status' => config('base.site_status'),
            'base_site_name' => config('base.site_name'),
            "base_site_logo" => config('base.site_logo'),
            "base_site_icp" => config('base.site_icp'),
        ];
    }

}